package webmarket.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.db.jpa.BasicLogEventEntity;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.message.Message;

import webmarket.common.CommonMethods;
import webmarket.jpacontrollers.UserJpaController;

/**
 * The persistent class for the log database table.
 * 
 */
@Entity
@Table(name = "log")
public class Log extends BasicLogEventEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	private int id;

	private User user;

	/**
	 * Constructor for JPA - reading
	 */
	public Log() {
		super(new Log4jLogEvent(0));
	}

	/**
	 * Constructor for Log4j - writing
	 */
	public Log(LogEvent event) {
		super(event);
		String username = CommonMethods.getCurrentUserName();
		if (username != null) {
			UserJpaController ujc = new UserJpaController();
			setUser(ujc.getByUsername(username));
		}
	}

	@Id
	public int getId() {
		return this.id;
	}

	public void setId(int id) {
		this.id = id;
	}

	private Marker marker;
	private Message message;
	private Level level;
	private long millis;
	private String loggerName;
	private Throwable throwable;

	@Override
	public void setMarker(Marker marker) {
		this.marker = marker;
	};

	@Override
	public void setMessage(Message message) {
		this.message = message;
	}

	@Override
	public void setLevel(Level level) {
		this.level = level;
	}

	@Override
	public void setMillis(long millis) {
		this.millis = millis;
	}

	@Override
	public void setLoggerName(String loggerName) {
		this.loggerName = loggerName;
	}

	@Override
	public void setThrown(Throwable throwable) {
		this.throwable = throwable;
	}

	public LogEvent getEvent() {
		return new Log4jLogEvent(loggerName, marker, null, level, message, throwable, null, null, null, null, millis);
	}

	@ManyToOne
	@JoinColumn(name = "userid")
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}